#include "xptSubmit.h"
#include "xptClient.h"
#include "../LMContext.h"

#define MAX_TRANSACTIONS	(4096)

// miner version string (for pool statistic)
char* minerVersionString = "xptMiner 1.7c";

minerSettings_t minerSettings = {0};

volatile uint32 monitorCurrentBlockHeight; // used to notify worker threads of new block data
volatile uint32 monitorCurrentBlockTime; // keeps track of current block time, used to detect if current work data is outdated

// stats
volatile uint32 totalCollisionCount = 0;
volatile uint32 totalShareCount = 0;
volatile uint32 totalRejectedShareCount = 0;
volatile uint32 total2ChainCount = 0;
volatile uint32 total3ChainCount = 0;
volatile uint32 total4ChainCount = 0;
volatile uint32 totalSieveCount = 0;


/*
 * Submit Riecoin share
 */
void xptMiner_submitShare(minerRiecoinBlock_t* block, uint8* nOffset, boost::shared_ptr<LMContext> context)
{
	uint32 passedSeconds = (boost::posix_time::microsec_clock::universal_time() - context->minerStartTime()).total_seconds();
	printf("[%02d:%02d:%02d] Share found! (Blockheight: %d)\n", (passedSeconds/3600)%60, (passedSeconds/60)%60, (passedSeconds)%60, block->height);
	EnterCriticalSection(&context->cs_xptClient);
	if( context->xptClient == NULL || xptClient_isDisconnected(context->xptClient, NULL) == true )
	{
		printf("Share submission failed - No connection to server\n");
		LeaveCriticalSection(&context->cs_xptClient);
		return;
	}
	// submit block
	xptShareToSubmit_t* xptShare = (xptShareToSubmit_t*)malloc(sizeof(xptShareToSubmit_t));
	memset(xptShare, 0x00, sizeof(xptShareToSubmit_t));
	xptShare->algorithm = ALGORITHM_RIECOIN;
	xptShare->version = block->version;
	xptShare->nTime = block->nTime;
	xptShare->nonce = 0;
	xptShare->nBits = block->nBits;
	memcpy(xptShare->prevBlockHash, block->prevBlockHash, 32);
	memcpy(xptShare->merkleRoot, block->merkleRoot, 32);
	memcpy(xptShare->merkleRootOriginal, block->merkleRootOriginal, 32);
	sint32 userExtraNonceLength = sizeof(uint32);
	uint8* userExtraNonceData = (uint8*)&block->uniqueMerkleSeed;
	xptShare->userExtraNonceLength = userExtraNonceLength;
	memcpy(xptShare->userExtraNonceData, userExtraNonceData, userExtraNonceLength);
	memcpy(xptShare->riecoin_nOffset, nOffset, 32);
	xptClient_foundShare(context->xptClient, xptShare);
	LeaveCriticalSection(&context->cs_xptClient);
}
